package com.peanut.service.impl;

import com.orm.mapper.BaseService;
import com.peanut.entity.Menu;
import com.peanut.entity.vo.MenuTreeVo;
import com.peanut.mapper.MenuMapper;
import com.peanut.mapper.RoleMenuMapper;
import com.peanut.service.MenuService;
import com.spring.annotation.Autowired;
import com.spring.annotation.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends BaseService<MenuMapper,Menu> implements MenuService {
	@Autowired
	private RoleMenuMapper roleMenuMapper;
	
	@Override
	public List<MenuTreeVo> queryMyMenuTree(int roleId) {
		List<Integer> roleMenuIds = roleMenuMapper.queryByRoleId(roleId);    // 角色拥有的全部菜单id
		
		List<MenuTreeVo> menuTreeVos = baseMapper.queryAllTopMenu();    // 拿到所有顶级菜单，所有角色
		List<Menu> menus = baseMapper.queryAllSonMenu();              // 拿到所有子级菜单，所有角色
		
		
		List<MenuTreeVo> collect1 = menuTreeVos.stream().filter(topMenu -> {
			return roleMenuIds.contains(topMenu.getId());
		}).collect(Collectors.toList());
		
		
		collect1.forEach(filterTopMenu ->{
			List<Menu> collect = menus.stream().filter(menu -> {
				return roleMenuIds.contains(menu.getId()) && menu.getParentId().equals(filterTopMenu.getId());
			}).collect(Collectors.toList());
			
			filterTopMenu.setChildren(collect);
		});
		
		
		return collect1;
	}
	
	@Override
	public List<MenuTreeVo> queryMenuTree() {
		List<MenuTreeVo> menuTreeVos = baseMapper.queryAllTopMenu();
		List<Menu> menus = baseMapper.queryAllSonMenu();
		
		menuTreeVos.forEach( menuTreeVo -> {
			menus.forEach( menu ->{
				if(menu.getParentId().equals( menuTreeVo.getId())){
					menuTreeVo.getChildren().add(menu);
				}
			});
		});
		return menuTreeVos;
	}
}
